<template>
	<view class="page">
		<view class="address">
			<view class=" u-m-l-20 u-m-r-20 u-m-t-20" v-if="cart_take.orderType == 'takecheck'">
				<view class="base-panel-box">
					<view class="item_single">购买成功后二维码券将自动发送在您的订单中</view>
				</view>
			</view>
	
			<view>
					<view class=" u-padding-20">
					    <view class="base-panel-box">
					      <view class="htitle">自提地点</view>
					      <view class="item">
					        {{shop_address}}
					      </view>
						</view>
					</view>
			</view>
		</view>
		<!-- 列表 -->
		
		<u-empty text="还没有选购商品" mode="car" icon="https://i.yodin.com/storage/empty/nocart.png" v-if="cart.length===0"></u-empty>
		<view  v-if="loadstatus">
			<view class="cart-list">
			<view v-if="cart.length>0" v-for="(shop,index) in cartgGroupedData">
				<view class="shop u-flex u-flex-between u-p-t-20 u-p-l-20 u-p-r-20">
					<view>{{shop.groupname}}</view>
					<view>{{$t('expressfee')}}：{{(shipping_fee*1).toFixed(2)}}</view>
				</view>
				<view class="cart-item" v-for="(goods,key) in shop.list">
					<view class="image-wrappers">
						<u--image :showLoading="true" :src="goods.cover_url" width="100%" height="auto" mode="widthFix" radius="12rpx"></u--image>
					</view>
					<view class="item-right">
						<text class="clamp title u-m-b-20" >{{goods.goods_name}}</text>
						<view v-if="goods.sku_name">{{goods.sku_name}}</view>
						<view class="u-flex u-flex-between">
							<view>
								<span class="price fuhao">{{site.money.symbol}}</span>
								<span class="price">{{goods.price}}</span>
							</view>
							<view class="btn-group">
								<button type="default" v-show="goodCartNum(goods.goods_id,goods.sku_id)" plain class="btn reduce_btn"
								 size="mini" hover-class="none" @tap="handleReduceFromCart(goods)">
									<u-icon name="minus" labelPos="bottom"></u-icon>
								</button>
								<view class="number" v-show="goodCartNum(goods.goods_id,goods.sku_id)">{{ goodCartNum(goods.goods_id,goods.sku_id) }}</view>
								<button type="primary" class="btn add_btn" size="min" hover-class="none" 
									@tap="handleAddToCart(goods,1)" >
									<u-icon name="plus" labelPos="bottom" color="color['u-bg-color']"></u-icon>
								</button>
							</view>
						</view>
						
					</view>
				</view>
			  <view class="u-flex u-flex-between u-padding-10 u-m-l-20 u-m-r-20" v-if="cart_take.orderType_take == 'out'&&cart_take.shopinfo.packing_fee > 0">
					<view class="">包装费</view>
					<view class="" >x1</view>
					<view class="item-right price">{{ parseFloat(cart_take.shopinfo.packing_fee) }}</view>
			  </view>
			  <view class="u-flex u-flex-between u-padding-10 u-m-l-20 u-m-r-20" v-if="cart_take.orderType_take == 'out'&&cart_take.shopinfo.delivery_cost > 0">
					<view class="">配送费</view>
					<view class="" >x1</view>
					<view class="item-right price">{{ parseFloat(cart_take.shopinfo.delivery_cost) }}</view>
			  </view>
			  
			</view>
			
			<view v-if="cart.length===0">
                <view class="u-font-32 u-font-bold u-padding-20 u-m-t-20">推荐热门</view>
				<goods-row :list="recommendGoods"></goods-row>
			</view>
			<u-gap height="70"></u-gap>
		</view> 
		<!-- 底部菜单栏 -->
		<view class="action-section" :style="'margin-bottom:'+height" v-if="cart.length>0">
			<view class="actionbox u-flex u-flex-between">
			<view class="u-flex-9 u-flex u-flex-between">
				<view class="u-p-r-30 u-flex-6">
					商品:
					<span class="price fuhao">{{site.money.symbol}}</span>
					<span class="price">{{(totalamount).toFixed(2)}}</span>
				</view>
				<view class=" u-flex-6">
					{{$t('expressfee')}}:
					<text v-if="userInfo.token">
						<span class="price fuhao">{{site.money.symbol}}</span>
						<span class="price">{{total_shipping_fee.toFixed(2)}}</span>
					</text>
					<text v-else> 请先登陆 </text>
				</view>
			</view>
			<view class="u-flex-3">
				<button type="primary" class="no-border confirm-btn" @click="createOrder">结算</button>
			</view>
			
			</view>
		</view>
		</view>
		<f-tabbar></f-tabbar>
	</view>
	
</template>

<script>

import { mapState, mapMutations } from 'vuex';
import base from '@/config/baseUrl.js';
import { api_goods_list,api_user_addresslist,api_order_save } from '@/config/api.js';
import goodsRow from "./module/goods-row";
import fTabbar from '@/components/module/f-tabbar/f-tabbar';
import { hidePageNavInWechatBrowser,isWechat } from '@/config/h5Utils';
export default {
  components: {
	  goodsRow,fTabbar
    },
    data() {
        return {
			loadstatus:false,
			height:'60px',
			cart:[],
			cartgGroupedData:[],//按shopid重组的购物车
			address_is_empty:true,
			addressData: [],
			recommendGoods:[],//购物车为空时的推荐商品
			shipping_fee:0,
			total_shipping_fee:0,
			totalamount:0,
			addr_id:'',
			ee:'',
			site:{
				money:{
					symbol:'',
				},
			},
			cart_take:[],
			userselect_addr_id:'',
			shop_address:''
        }
    },
  watch: {
    //显示空白页
    addressData(e) {
      let empty = e == undefined || e.length <= 0 ? true : false;
      if (this.address_is_empty !== empty) {
        this.address_is_empty = empty;
      }
	  if (empty == false){
		    this.shipping_fee=e.shipping_fee
			this.addr_id=e.addr_id
			this.rest_buildcartGroup()
	  }
    },
  },
	computed:{
	    ...mapState(['PrimaryColor','extConfig','userInfo','siteInfo']),
			goodCartNum() {	//计算单个商品添加到购物车的数量
				return (id,skuid) => this.cart.reduce((acc, cur) => {
						if(cur.id === id&&cur.sku_id === skuid) {
							return acc += cur.num
						}
						return acc
					}, 0)
			},
	},
	onReady() {
		if (isWechat()){
			this.height = '90px'
		}
		hidePageNavInWechatBrowser();
	},
    async onLoad(e) {
		uni.setNavigationBarTitle({title: this.$t('pagetitle.cart')});
		this.getDefaultAddress()
		if (e.state=='buy'){
			this.cart = uni.getStorageSync('buy')
			this.ee=e.state
		}
		this.cart_take = uni.getStorageSync('cart_take')
		this.userselect_addr_id=uni.getStorageSync('userselect_addr_id')
		this.shop_address=uni.getStorageSync('userselect_addr_id_name')
		await this.$store.dispatch("getsiteInfo",{bid:this.extConfig.bid}).then(rs=>{
				this.site=rs
		});
    },
	onShow(){
			this.totalamount=0
			this.total_shipping_fee=0
		if (this.ee==''){
			this.cart = uni.getStorageSync('cart')
		}else{
			this.ee=''
		}

		this.rest_buildcartGroup()
		this.recommend()
	},
	onPullDownRefresh() {
		this.cart = uni.getStorageSync('cart')
		this.rest_buildcartGroup()
		this.recommend()
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 100);
	},
    methods: {
		createOrder(){
			api_order_save({
				cartgGroupedData:JSON.stringify(this.cartgGroupedData),
				addr_id:this.addr_id
			}).then((res) => {
				uni.setStorageSync('cart', [])
				this.$tools.goJump('/pagesPackageA/order/pay',{order_code:res.order_code},'','launch')
			}).catch((error) => {});
		},
		getDefaultAddress(){
			api_user_addresslist({
				find_users_id:this.userInfo.member_id
			}).then((res) => {
					this.loadstatus=true  //为加载siteInfo而延时，否则刷新js出错
					res.roomlist.forEach((addr,index) => {
						if (this.address_is_empty==true){
						   this.addressData=addr
						   this.address_is_empty = false; 
						}
					    if (addr.is_default==1){
						   this.addressData=addr
						   this.address_is_empty = false; 
					    }
					})
			}).catch((error) => {});
		},
		recommend(){
			if (this.cart.length<=1){
				api_goods_list({
				  page:1,
				  limit:6,
				  search_field:'is_hot',
				  search_exp:'=',
				  search_value:'1',
				  thumb_width:300,
				  thumb_height:300
				}).then((res) => {
				  this.recommendGoods=res.list
				}).catch((error) => {});
			}
		},
		//购物车按 shopid分组
		rest_buildcartGroup(){
			const cart_count = Object.keys(this.cart).length
			console.log('this.cart',this.cart)
			if (cart_count==0){return}
			this.totalamount = 0
			this.cartgGroupedData = this.cart.reduce( (acc, cur) => {
				  let key
				  if (cur.group_id==''){
					key='g'
				  }else{
					key=cur.group_id
				  }
				  if (!acc[key]) acc[key] = {}
				  if (!acc[key]['list']) acc[key]['list'] = []
					acc[key].groupname=cur.group_name==''?'':cur.group_name
					acc[key].group_id = cur.group_id
					acc[key].list.push(cur)
					this.totalamount+=parseFloat(cur.price)*parseFloat(cur.num)
				  return acc
				}, {})
				this.total_shipping_fee=0
			  for (let [k, v] of Object.entries(this.cartgGroupedData)) {
				this.total_shipping_fee+=parseFloat(this.shipping_fee)
			  }
		},
		handleReduceFromCart( good) {
			const cart_count = Object.keys(this.cart).length
			if (cart_count==0){return}
				const index = this.cart.findIndex(item => {
						if(good.sku_id>0) {
							return (item.id === parseFloat(good.goods_id)) && (item.sku_id === good.sku_id)
						} else {
							return item.id === parseFloat(good.goods_id)
						}
				})
				this.cart[index].num -= 1
				if(this.cart[index].num <= 0) {
					this.cart.splice(index, 1)
				}
				uni.setStorageSync('cart', this.cart)
				this.rest_buildcartGroup()
		},
		handleAddToCart(good, num) {	//添加到购物车
			const cart_count = Object.keys(this.cart).length
			if (cart_count==0){return}
					const index = this.cart.findIndex(item => {
						if(good.sku_id>0) {
							return (item.id === parseFloat(good.goods_id)) && (item.sku_id === good.sku_id)
						} else {
							return item.id === parseFloat(good.goods_id)
						}
					})
					if(index > -1) {
						this.cart[index].num += num
					}
					uni.setStorageSync('cart', this.cart)
					this.rest_buildcartGroup()
		},
    },

}
</script>

<style lang='scss'>
	/deep/.uni-page-body{
		background: #fff;
	}
	.address{background: #f9f9f9;}
	.page {
	/* 购物车列表项 */
	.cart-item {
		display: flex;
		position: relative;
		padding: 30upx 40upx;
		border-bottom: #e8e8e8 solid 1px;

		.image-wrappers { 
			width: 180upx !important;
			height: 180upx !important;
			flex-shrink: 0;
			position: relative;

			img { 
				width: 230upx !important;
				height: 230upx !important;
				border-radius: 8upx;
			}
		} 

		.checkbox {
			position: absolute;
			left: -16upx;
			top: -16upx;
			z-index: 8;
			font-size: 44upx;
			line-height: 1;
			padding: 14upx;
			background: #fff;
			border-radius: 50px;
		}

		.item-right {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			position: relative;
			padding-left: 30upx;
			.title,.price {
				line-height: 40upx;
			}

			.attr {
				height: 50upx;
				line-height: 50upx;
			}

			.price {
				height: 50upx;
				line-height: 50upx;
			}

		}


	}

	/* 底部栏 */
	.action-section {
		margin-bottom:100upx;
		bottom: 30upx;
		position: fixed;
		width:100vw;
		z-index: 95;
		
		.actionbox{
			height: 100upx;
			width: 95%;
			margin: auto;
			padding: 0 30upx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .1);
			border-radius: 16upx;
		}
		.confirm-btn {
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			height: 76upx;
			line-height: 76upx;
			box-shadow: 1px 2px 3px rgba(217, 60, 93, 0.72)
		}
	}

	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked {
	}

}	
	/*地址分割线*/
  .a-bg {
    position: absolute;
    left: 0;
    bottom: 0;
    display: block;
    width: 100%;
    height: 5upx;
  }
								.btn-group {
									display: flex;
									justify-content: space-between;
									align-items: center;
									position: relative;

									.btn {
										padding: 0rpx;
										font-size: 24rpx;
										height: 44rpx;
										line-height: 100%;
										display: flex;
										justify-content: center;
										align-items: center;
										&.property_btn {
											border-radius: 24rpx;
										}
										&.dis{
											background:#ffffff;
										}

										&.add_btn,
										&.reduce_btn {
											padding: 0;
											width: 44rpx;
											border-radius: 44rpx;
										}
										&.add_btn,&.property_btn{
											background: #5ac725;
										}
									}

									.dot {
										position: absolute;
										background-color: #ffffff;
										border: 1px solid #5ac725;
										color: #5ac725;
										font-size: 24rpx;
										width: 36rpx;
										height: 36rpx;
										line-height: 36rpx;
										text-align: center;
										border-radius: 100%;
										right: -12rpx;
										top: -10rpx;
									}

									.number {
										width: 44rpx;
										height: 44rpx;
										line-height: 44rpx;
										text-align: center;
									}
								}
  
</style>

